/**
 * Created by Ysssssss on 2021/5/11.
 */

import React, { useState, useEffect, useRef, useCallback } from 'react'
import {priceFenToYuan, priceYuanToFen} from "@utils/priceConversion";
import {Row, Col, Input, InputNumber, Table} from "antd";
import InputNumberWithSuffix from "@common/presentational/InputNumberWithSuffix";


const getALlStandard = (arrays) => {
    if (!arrays.length) return []
    if (arrays.length === 1) return arrays[0].map(item => [ item ])
    return arrays.reduce((arr1, arr2) =>
        arr1.flatMap(propertyName =>
            arr2.map(propertyName2 =>
                Array.isArray(propertyName) ? [...propertyName, propertyName2] : [propertyName, propertyName2]
            )
        )
    )
}


const ProductDetailStandard = props => {
    const { value = [], onChange, groups = [], productNature } = props
    const [ standardInfoMap, setStandardInfoMap ] = useState({})

    useEffect(() => {
        let _standardInfoMap = {}
        value.forEach(item => {
            if (item.price === '' && item.weight === '') return;
            let name = item.items.map(subItem => `${subItem.name}|---|${subItem.item}`).join('|~~~|')
            _standardInfoMap[name] = {
                price: item.price,
                weight: item.weight
            }
        })
        setStandardInfoMap(_standardInfoMap)
    }, [])

    useEffect(() => {
        let groupItems = groups.map(group => group.items.map(item => `${group.name}|---|${item}`))
        let allStandardList = getALlStandard(groupItems)
        let _skus = []
        allStandardList.map(standardArray => {
            let name = standardArray.join('|~~~|')
            let _items = standardArray.map(standard => {
                let [_name, _item] = standard.split('|---|')
                return {
                    name: _name,
                    item: _item
                }
            })
            _skus.push({
                price: '',
                weight: productNature === 2 ? 0 : '',
                items: _items,
                ...(standardInfoMap[name] || {})
            })
        })
        onChange(_skus)
    }, [groups, standardInfoMap])

    const changeStandardInfoMap = (item, itemKey, itemValue) => {
        let name = item.items.map(subItem => `${subItem.name}|---|${subItem.item}`).join('|~~~|')
        setStandardInfoMap({
            ...standardInfoMap,
            [name]: {
                ...standardInfoMap[name],
                [itemKey]: itemValue
            }
        })
    }

    const handleStandardPriceChange = (index, price) => {
        changeStandardInfoMap(value[index], 'price', priceYuanToFen(price))
    }

    const handleStandardWeightChange = (index, weight) => {
        changeStandardInfoMap(value[index], 'weight', weight)
    }


    let columns = [{
        title: '规格属性',
        dataIndex: 'items',
        key: 'items',
        render: text => text.map(item => item.item).join('， ')
    },{
        title: '价格（元）',
        dataIndex: 'price',
        key: 'price',
        render: (text, record, index) => (
            <InputNumber
                min={0.01}
                max={100000000}
                step={1}
                precision={2}
                value={priceFenToYuan(text)}
                style={{ width: '180px' }}
                onChange={handleStandardPriceChange.bind(this, index)}
            />
        )
    }]
    if (productNature !== 2) {
        columns.push({
            title: '重量（g）',
            dataIndex: 'weight',
            key: 'weight',
            render: (text, record, index) => (
                <InputNumber
                    min={0}
                    max={1000000000}
                    step={1}
                    precision={2}
                    value={text}
                    style={{ width: '180px' }}
                    onChange={handleStandardWeightChange.bind(this, index)}
                />
            )
        })
    }

    return (
        <Row>
            <Col span={4}>规格设置</Col>
            <Col span={20}>
                <Table
                    columns={columns}
                    pagination={false}
                    dataSource={value.map((v,index) => ({...v, key: `standard_${index}`}))}
                />
            </Col>
        </Row>
    )
}

const ProductDetailNoStandard = props => {
    const { value = [], onChange, productNature } = props
    const { price = '', weight = '' } = value[0] || {}

    useEffect(() => {
        if (!value.length || value[0].items.length) {
            onChange([{
                price: '',
                weight: productNature === 2 ? 0 : '',
                items: []
            }])
        }
    }, [value])

    const handleStandardPriceChange = (inputValue) => {
        onChange([{
            price: priceYuanToFen(inputValue),
            weight,
            items: []
        }])
    }

    const handleStandardWeightChange = (inputValue) => {
        onChange([{
            price,
            weight: inputValue,
            items: []
        }])
    }

    return (
        <>
            <Row>
                <Col span={4}>商品价格</Col>
                <Col span={20}>
                    <InputNumberWithSuffix
                        min={0.01}
                        step={1}
                        max={100000000}
                        precision={2}
                        value={priceFenToYuan(price)}
                        className="w-100"
                        onChange={handleStandardPriceChange}
                        suffix="元"
                    />
                </Col>
            </Row>
            { productNature === 2 ? null : (
                <Row>
                    <Col span={4}>商品重量</Col>
                    <Col span={20}>
                        <InputNumberWithSuffix
                            min={0}
                            max={1000000000}
                            step={1}
                            precision={2}
                            value={weight}
                            className="w-100"
                            onChange={handleStandardWeightChange}
                            suffix="g"
                        />
                    </Col>
                </Row>
            ) }
        </>
    )
}

const ProductDetailStandardHandle = props => {
    const { groups = [], value } = props
    if (value === undefined) return null
    return groups.length ? <ProductDetailStandard { ...props }/> : <ProductDetailNoStandard { ...props }/>
}

export default ProductDetailStandardHandle
